package com.groupbuying.cheetah.order.orderManagement.service.impl;

import com.groupbuying.cheetah.common.FilterContextHandler;
import com.groupbuying.cheetah.common.PageUtils;
import com.groupbuying.cheetah.common.Query;
import com.groupbuying.cheetah.order.orderManagement.constans.OrderUshopEnumConstants;
import com.groupbuying.cheetah.order.orderManagement.dao.OrderUshopDao;
import com.groupbuying.cheetah.order.orderManagement.dao.SettleUshopSplitMaininfoDao;
import com.groupbuying.cheetah.order.orderManagement.domain.OrderUshopDO;
import com.groupbuying.cheetah.order.orderManagement.domain.SettleUshopSplitMaininfoDO;
import com.groupbuying.cheetah.order.orderManagement.dto.OrderUshopDTO;
import com.groupbuying.cheetah.order.orderManagement.dto.OrderUshopFirstDTO;
import com.groupbuying.cheetah.order.orderManagement.service.OrderService;
import com.groupbuying.cheetah.pay.dao.PayInfoDao;
import com.groupbuying.cheetah.pay.dao.PayOrderRelDao;
import com.groupbuying.cheetah.pay.domain.PayInfoDO;
import com.groupbuying.cheetah.pay.domain.PayOrderRelDO;
import com.groupbuying.cheetah.utils.JsonUtils;
import com.groupbuying.cheetah.utils.apiresult.ApiResult;
import com.groupbuying.cheetah.utils.apiresult.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService{

    public static final Logger LOGGER = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Autowired
    private OrderUshopDao orderUshopDao;

    @Autowired
    private PayOrderRelDao payOrderRelDao;

    @Autowired
    private PayInfoDao payInfoDao;

    @Autowired
    private SettleUshopSplitMaininfoDao settleUshopSplitMaininfoDao;


    @Override
    public OrderUshopDO get(String orderId) {
        return orderUshopDao.get(orderId);
    }

    @Override
    public List<OrderUshopDO> list(Map<String, Object> map) {
        return orderUshopDao.list(map);
    }

    @Override
    public int count(Map<String, Object> map) {
        return orderUshopDao.count(map);
    }

    /**
     * 根据时间和counterId查询
     *
     * @param
     * @return
     */
    @Override
    public ApiResult getDataByCustomer(Map<String, Object> param) {
        String counterId = param.get("counterId").toString();
        Object gmtCreat = param.get("gmtCreate");
        //开始时间
        Object tempStartTime = param.get("startTime");
        String startTime = tempStartTime == null ? "" : tempStartTime.toString();
        //结束时间
        Object tempEndTime = param.get("endTime");
        String endTime = tempEndTime == null ? "" : tempEndTime.toString();

        String gmtCreate = gmtCreat == null ? "" : gmtCreat.toString();
        System.out.println("counterId:"+counterId);
        if (StringUtils.isEmpty(counterId)) {
            return ApiResult.failure("参数不能为空");
        }
        LOGGER.info("时间为:{}，收银台ID:{}", gmtCreate, counterId);
        //格式化时间戳
        // String format = DateUtils.format(new Date(Long.valueOf(gmtCreate)),DateUtils.YMD);
        String start = DateUtils.format(new Date(Long.valueOf(startTime)), DateUtils.YMDHMS);
        String end = DateUtils.format(new Date(Long.valueOf(endTime)), DateUtils.YMDHMS);
//         Long start = Long.valueOf(startTime);
//        Long end = Long.valueOf(endTime);

        //订单状态赋值
        String orderState[] = new String[3];
        orderState[0] = OrderUshopEnumConstants.ENUM_ORDERSTATE_PAY;
        orderState[1] = OrderUshopEnumConstants.ENUM_ORDERSTATE_REFUNDED;
        orderState[2] = OrderUshopEnumConstants.ENUM_ORDERSTATE_REFUNDFAIL;
        param.put("orderState", orderState);
        //param.put("gmtCreate", format);
        param.put("startTimes", start);
        param.put("endTimes", end);
        LOGGER.info("格式化开始查询时间{}", start);
        LOGGER.info("格式化结束查询时间{}", end);
        Query query = new Query(param);

        //查询订单列表
        List<OrderUshopFirstDTO> orderUshopDOFirst = orderUshopDao.getOrderByCustomer(query);
        List<OrderUshopDTO> orderUshopDO = new ArrayList<>();
        List<String> orderIds = new ArrayList<>();
        for(OrderUshopFirstDTO orderUshopFirstDTO: orderUshopDOFirst){
            orderIds.add(orderUshopFirstDTO.getOrderId());
            OrderUshopDTO orderUshopDTO = new OrderUshopDTO();
            orderUshopDTO.setGmtCreateStr(orderUshopFirstDTO.getGmtCreateStr());
            orderUshopDTO.setGmtModifiedStr(orderUshopFirstDTO.getGmtModifiedStr());
            orderUshopDTO.setClosedTimeStr(orderUshopFirstDTO.getClosedTimeStr());

            PayOrderRelDO payOrderRelDO = payOrderRelDao.getByOrderId(orderUshopFirstDTO.getOrderId());
            PayInfoDO payInfoDO = payInfoDao.get(payOrderRelDO.getId());

            switch (payInfoDO.getPayType()){
                case "1":{
                    orderUshopDTO.setPayType("微信支付");
                }break;
                case "2":{
                    orderUshopDTO.setPayType("支付宝支付");
                }break;
                case "3":{
                    orderUshopDTO.setPayType("积分支付");
                }break;
                case "4":{
                    orderUshopDTO.setPayType("余额支付");
                }break;
                default:{
                    orderUshopDTO.setPayType("未知");

                }break;
            }

            orderUshopDTO.setPayMoney(payInfoDO.getPayMoney());
            orderUshopDTO.setPayCur(payInfoDO.getPayCur());
            orderUshopDTO.setPayBalance(payInfoDO.getPayBalance());


            //其他不重要数据
            orderUshopDTO.setOrderId(orderUshopFirstDTO.getOrderId());
            orderUshopDTO.setIsDelete(orderUshopFirstDTO.getIsDelete());
            orderUshopDTO.setGmtCreate(orderUshopFirstDTO.getGmtCreate());
            orderUshopDTO.setGmtModified(orderUshopFirstDTO.getGmtModified());
            orderUshopDTO.setCustomerId(orderUshopFirstDTO.getCustomerId());
            orderUshopDTO.setCounterId(orderUshopFirstDTO.getCounterId());
            orderUshopDTO.setDealState(orderUshopFirstDTO.getDealState());
            orderUshopDTO.setOrderState(orderUshopFirstDTO.getOrderState());
            orderUshopDTO.setOrderPrice(orderUshopFirstDTO.getOrderPrice());
            orderUshopDTO.setOpxRuleId("001".equals(orderUshopDTO.getOrderId().substring(4,7))?"优惠买单":"够样优店");
            orderUshopDTO.setClosedTime(orderUshopFirstDTO.getClosedTime());
            orderUshopDTO.setStateNote(orderUshopFirstDTO.getStateNote());
            orderUshopDTO.setGmtCreateStr(orderUshopFirstDTO.getGmtCreateStr());
            orderUshopDTO.setGmtModifiedStr(orderUshopFirstDTO.getGmtModifiedStr());
            orderUshopDTO.setClosedTimeStr(orderUshopFirstDTO.getClosedTimeStr());
            orderUshopDTO.setStoreAmount(new BigDecimal(settleUshopSplitMaininfoDao.getStoreAmountByOrderId(orderUshopFirstDTO.getOrderId())));
            orderUshopDO.add(orderUshopDTO);
        }
        
        //查询分页需要总数据量
        int total = orderUshopDao.countForOrder(query);
        //包装分页对象
        PageUtils pageUtils = new PageUtils(orderUshopDO, total);

        //查询当前时间的收入和订单完成数量
        Map<String, Object> map = new HashMap<>();
        String orderstates[] = new String[]{OrderUshopEnumConstants.ENUM_ORDERSTATE_PAY,OrderUshopEnumConstants.ENUM_ORDERSTATE_REFUNDFAIL};
        map.put("orderState", orderstates);
        map.put("counterId", counterId);
        // map.put("gmtCreate",format);
        map.put("startTimes", start);
        map.put("endTimes", end);
        map.put("opxRuleId", param.get("opxRuleId"));
        BigDecimal amountMoney = orderUshopDao.countOderMoney(map);
        //统计实收金额
        LOGGER.error("OrderServiceImpl-->getDataByCustomer countPayMoney params:::"+map);
        BigDecimal payMoney = countPayMoney(map);
//        BigDecimal payMoney = orderUshopDao.countPayMoney(map);
        map.put("orderState", orderstates);
        LOGGER.error("OrderServiceImpl-->getDataByCustomer countOderNumber params:::"+ JsonUtils.objectToJson(map));
        int countOderNumber = orderUshopDao.countOderNumber(map);

        //包装返回参数
        Map<String, Object> result = new HashMap<>();
        //列表展示包括（已支付+退款失败+退款成功）
        result.put("pageUtils", pageUtils);
        //订单总金额（已支付+退款失败）
        result.put("amountMoney", amountMoney);
        //订单数量（已支付+退款失败）
        result.put("countOderNumber", countOderNumber);
        //实收总金额（已支付+退款失败）
        result.put("totalPayMoney",payMoney);
        return ApiResult.success(result);
    }

    /**
     * 根据和counterId查询
     *
     * @param
     * @param
     * @return
     */
    @Override
    public ApiResult getOrderByCountId(Map<String, Object> param) {
        Object par = param.get("counterId");
        String counterId = par == null ? "" : par.toString();
        //String counterId = param.get("counterId").toString();
        System.out.println("counterId2:"+counterId);
        if (StringUtils.isEmpty(counterId)) {
            return ApiResult.failure("参数不能为空");
        }

		/*param.put("orderState","1");
        param.put("orderState","3");*/
		//订单状态
        String orderState[] = new String[3];
        orderState[0] = OrderUshopEnumConstants.ENUM_ORDERSTATE_PAY;
        orderState[1] = OrderUshopEnumConstants.ENUM_ORDERSTATE_REFUNDED;
        orderState[2] = OrderUshopEnumConstants.ENUM_ORDERSTATE_REFUNDFAIL;
        param.put("orderState", orderState);
        Query query = new Query(param);

        List<OrderUshopDTO> orderUshopDO = orderUshopDao.getDataByCustomer(query);

        LOGGER.info("查询信息：{}",orderUshopDO);
        Map<String, Object> map = new HashMap<>();
        String orderstates[] = new String[]{OrderUshopEnumConstants.ENUM_ORDERSTATE_PAY,OrderUshopEnumConstants.ENUM_ORDERSTATE_REFUNDFAIL};
        map.put("counterId", counterId);
        map.put("orderState", orderstates);
        //统计余额
        BigDecimal amountMoney = orderUshopDao.countOderMoney(map);

        int countOderNumber = orderUshopDao.countOderNumber(map);
        //统计实付金额
//        BigDecimal payMoney = orderUshopDao.countPayMoney(map);
        BigDecimal payMoney = countPayMoney(map);
        int total = orderUshopDao.countForOrder(query);
        PageUtils pageUtils = new PageUtils(orderUshopDO, total);
        Map<String, Object> result = new HashMap<>();
        result.put("pageUtils", pageUtils);
        result.put("amountMoney", amountMoney);
        result.put("countOderNumber", countOderNumber);
        result.put("totalPayMoney",payMoney);
        return ApiResult.success(result);



    }

    /**
     * @param
     * @return
     */
    @Override
    public ApiResult getOrderByGmtTime(Map<String, Object> param) {
        Object par = param.get("gmtCreate");
        Long time = par == null ? 0 : Long.valueOf(String.valueOf(par));
        //Long time = Long.valueOf(String.valueOf(param.get("gmtCreate")));
        String orderState[] = new String[3];
        orderState[0] = OrderUshopEnumConstants.ENUM_ORDERSTATE_PAY;
        orderState[1] = OrderUshopEnumConstants.ENUM_ORDERSTATE_REFUNDED;
        orderState[2] = OrderUshopEnumConstants.ENUM_ORDERSTATE_REFUNDFAIL;
        param.put("orderState", orderState);
        if (time == null) {
            return ApiResult.failure("参数不能为空");
        }
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String format = formatter.format(time);
        param.put("gmtCreate", format);
        LOGGER.info("传入参数" + par);
        LOGGER.info("订单筛选时间" + format);
        Query query = new Query(param);
        List<OrderUshopDTO> orderUshopDO = orderUshopDao.getDataByCustomer(query);

        int total = orderUshopDao.countForOrder(query);
        PageUtils pageUtils = new PageUtils(orderUshopDO, total);
        return ApiResult.success(pageUtils);
    }

    @Override
    public ApiResult getTodayOrder(Map<String, Object> param) {
        Object par = param.get("counterId");
        String accountId = FilterContextHandler.getUserID();
        String counterId = par == null ? "" : par.toString();
        if (StringUtils.isEmpty(counterId)) {
            ApiResult.failure("参数不能为空");
        }
        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String gmtCreate = date + " " + "00:00:00";
        String orderState[] = new String[3];
        orderState[0] = OrderUshopEnumConstants.ENUM_ORDERSTATE_PAY;
        orderState[1] = OrderUshopEnumConstants.ENUM_ORDERSTATE_REFUNDED;
        orderState[2] = OrderUshopEnumConstants.ENUM_ORDERSTATE_REFUNDFAIL;
        param.put("orderState", orderState);
        param.put("gmtCreate", gmtCreate);
        //param.put("gmtCreate",endTime);
        int count = orderUshopDao.countOrder(param);
        return ApiResult.success(count);


    }

    @Override
    public ApiResult countOrder(Map<String, Object> param) {
        //String counterId = param.get("counterId").toString();
        Object par = param.get("counterId");
        String counterId = par == null ? "" : par.toString();
        if (StringUtils.isEmpty(counterId)) {
            ApiResult.failure("参数不能为空");
        }
        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String gmtCreate = date + " " + "00:00:00";
        //String gmtCreate = "2019-06-06 00:00:04";
        //LOGGER.info("当前时间为："+date);
        String orderState[] = new String[3];
        orderState[0] = OrderUshopEnumConstants.ENUM_ORDERSTATE_PAY;
        orderState[1] = OrderUshopEnumConstants.ENUM_ORDERSTATE_REFUNDFAIL;
        //orderState[1]=OrderUshopEnumConstants.ENUM_ORDERSTATE_REFUNDED;
        // orderState[2] =OrderUshopEnumConstants.ENUM_ORDERSTATE_REFUNDFAIL;
        param.put("orderState", orderState);
        param.put("gmtCreate", gmtCreate);
        int count = orderUshopDao.countOrder(param);
        return ApiResult.success(count);

    }

    private BigDecimal countPayMoney(Map<String,Object> params){
        String[] orderState = new String[]{OrderUshopEnumConstants.ENUM_ORDERSTATE_PAY,OrderUshopEnumConstants.ENUM_ORDERSTATE_REFUNDFAIL,OrderUshopEnumConstants.ENUM_ORDERSTATE_REFUNDED};
        params.put("orderState",orderState);
        List<String> settleIds = orderUshopDao.getSettleIds(params);
        orderState = new String[]{OrderUshopEnumConstants.ENUM_ORDERSTATE_REFUNDED};
        params.put("orderState",orderState);
        List<String> refundIds = orderUshopDao.getRefundIds(params);
        List<String> externalId = new ArrayList<>();
        externalId.addAll(settleIds);
        externalId.addAll(refundIds);
        if(externalId.size()>0){
            LOGGER.error("OrderServiceImpl-->countPayMoney params:::"+externalId);
        }else{
            LOGGER.error("OrderServiceImpl-->countPayMoney params is null");
            return new BigDecimal("0.00");
        }

        BigDecimal countPayMoney = null == orderUshopDao.countPayMoney(externalId)?new BigDecimal("0.00"):orderUshopDao.countPayMoney(externalId);

        return countPayMoney;
    }


}
